<template>
  <PlusDialogForm
    ref="formRef"
    v-model:visible="visible"
    v-model="form"
    :form="{ columns, labelWidth: 100, labelPosition: 'right' }"
    :dialog="{ title: '添加用户', confirmLoading: loading }"
    @confirm="submit"
  >
    <template #plus-field-password>
      <el-input
        v-model="form.password"
        placeholder="请输入密码"
        type="password"
        show-password
        :minlength="6"
      />
    </template>
    <template #plus-field-checkpass>
      <el-input
        v-model="form.checkpass"
        placeholder="请再次输入密码"
        type="password"
        show-password
        :minlength="6"
      />
    </template>
    <template #plus-field-warehouseId>
      <k-select-http
        v-if="visible"
        v-model="form.warehouseId"
        paramsKey="searchValue"
        :immediately="true"
        :httpfn="getWarehouseList"
        :keyprops="{ label: 'name', value: 'warehouseId' }"
      />
    </template>
  </PlusDialogForm>
</template>

<script setup lang="ts">
import { computed, ref, watch, nextTick } from "vue";
import { ElMessage } from "element-plus";
import {
  type PlusColumn,
  PlusDialogForm,
  type FieldValues
} from "plus-pro-components";
import kSelectHttp from "@/components/k-select-http/index.vue";
import { allListApi as getWarehouseList } from "@/api/warehouse";
import { allListApi as getDeptsListApi } from "@/api/system/dept";
import { addApi } from "@/api/system/user";

const props = defineProps({
  // 最后是否要联网提交
  online: {
    default: true,
    type: Boolean
  }
});

const initForm = () => {
  return {
    roleName: "管理员",
    password: "",
    checkpass: "",
    warehouseId: "",
    deptId: "",
    userName: "",
    nickName: ""
  };
};
const form = ref(initForm());

const columns: PlusColumn[] = [
  {
    label: "角色",
    prop: "roleName",
    valueType: "text"
  },
  {
    label: "账号",
    prop: "userName",
    rules: { required: true, message: "请输入账号", trigger: "blur" }
  },
  {
    label: "用户名称",
    prop: "nickName",
    rules: { required: true, message: "请输入用户名称", trigger: "blur" }
  },
  {
    label: "工具室",
    prop: "warehouseId",
    hideInForm: computed(() => !props.online),
    rules: {
      required: true,
      message: "请选择工具室",
      trigger: "change"
    }
  },
  {
    label: "组织",
    prop: "deptId",
    valueType: "cascader",
    hideInForm: computed(() => {
      return form.value.warehouseId ? false : true;
    }),
    rules: { required: true, message: "请选择组织", trigger: "change" },
    fieldProps: computed(() => ({
      props: {
        checkStrictly: false, // 是否每一层可选
        label: "deptName",
        value: "deptId",
        children: "childDeptVos"
      }
    })),
    options: computed(() => {
      return deptList.value;
    })
  },
  {
    label: "密码",
    prop: "password",
    required: true,
    trigger: "blur",
    rules: {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          callback(new Error("请输入密码"));
        } else if (value.length < 6) {
          callback(new Error("密码最少设置6位以上"));
        } else {
          callback();
        }
      }
    }
  },
  {
    label: "确认密码",
    prop: "checkpass",
    rules: [
      {
        required: true,
        message: "两次密码不一样",
        validator: (rule: any, value: any, callback: any) => {
          if (!value) {
            callback(new Error("请再次输入密码"));
          } else if (value !== form.value.password) {
            callback(new Error("两次密码不一样"));
          } else {
            callback();
          }
        }
      }
    ]
  }
];

const visible = ref(false);
const formRef = ref(null);
const show = (formdata?: Object) => {
  visible.value = true;
  nextTick(() => {
    formRef?.value?.formInstance?.clearValidate();
    form.value = initForm();
  });
};
defineExpose({ show });
const loading = ref(false);
const emit = defineEmits(["confirm"]);
const submit = () => {
  const { deptId, userName, nickName, password, warehouseId } = form.value;
  const params = {
    deptId: deptId[deptId.length - 1],
    userName,
    nickName,
    password,
    warehouseId,
    status: 0
  };
  if (!props.online) {
    visible.value = false;
    return emit("confirm", { params, addApi });
  }
  addApi(params)
    .then(res => {
      loading.value = false;
      ElMessage.success("新增用户成功");
      emit("confirm", [{ ...params, userId: res.data }]);
      visible.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};

/* 组织相关 */
const deptList = ref([]);
const getDeptsList = async warehouseId => {
  const res = await getDeptsListApi({ warehouseId });
  form.value.deptId = "";
  deptList.value = res.data as any[];
};
watch(
  () => form.value.warehouseId,
  (val, oldVal) => {
    if (val && val !== oldVal) {
      getDeptsList(val);
    }
  }
);
</script>
